﻿package com.cqlfn.business.data.datapairingfill.service.impl;

import com.alibaba.fastjson.JSON;
import com.cqlfn.business.busData.dao.syn.SynDao;
import com.cqlfn.business.data.configManagement.entity.CfgColumn;
import com.cqlfn.business.data.configManagement.entity.CfgTable;
import com.cqlfn.business.data.configManagement.repository.CfgColumnRepository;
import com.cqlfn.business.data.configManagement.repository.CfgTableRepository;
import com.cqlfn.business.data.datapairingfill.bean.DataPairingUpload;
import com.cqlfn.business.data.datapairingfill.bean.LatestColumn;
import com.cqlfn.business.data.datapairingfill.dao.DataPairingFillDao;
import com.cqlfn.business.data.datapairingfill.repository.LatestColumnRepository;
import com.cqlfn.business.data.datapairingfill.service.DataPairingFillService;
import com.cqlfn.business.data.erp.DemandSide.service.AsyncQueryDataService;
import com.cqlfn.business.data.erp.DemandSide.service.AsyncSaveDataService;
import com.cqlfn.business.warehouseData.service.SynWarehouseDataService;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Pageable;
import org.springframework.stereotype.Service;
import org.springframework.util.StringUtils;

import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.*;
import java.util.concurrent.ConcurrentHashMap;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

/**
 * @ClassName ChooseTableServiceImpl
 * @Description 得到所有表的service实现
 * @Author yuanfeng
 * @Date 2019/8/8 13:46
 * @Version 1.0
 **/

@Service
public class DataPairingFillServiceImpl implements DataPairingFillService {

    private static final Logger LOGGER = LoggerFactory.getLogger(DataPairingFillServiceImpl.class);

    @Autowired
    private DataPairingFillDao dataPairingFillDao;

    @Autowired
    private AsyncSaveDataService asyncSaveDataService;

    @Autowired
    private SynWarehouseDataService synWarehouseDataService;

    @Autowired
    private SynDao synDaoImpl;

    @Autowired
    private CfgColumnRepository cfgColumnRepository;

    @Autowired
    private CfgTableRepository cfgTableRepository;

    @Autowired
    private AsyncQueryDataService asyncQueryDataService;

    @Autowired
    private LatestColumnRepository latestColumnRepository;

    /**
     * @return 把得到的所有表返回
     * @Description:得到所有表
     * @Param null
     * @date: 2019/8/12 9:52
     */

    @Override
    public List<Map<String, Object>> getAllTables() {

        Map<String, Object> mapTable = new HashMap<>();
        List<Map<String, Object>> listTable = new ArrayList<>();
        Iterator<CfgTable> iterator = null;
        try {
            Iterable<CfgTable> allTables = dataPairingFillDao.getAllTables();
            iterator = allTables.iterator();
        } catch (Exception e) {
            LOGGER.error(e + "");
            e.printStackTrace();
        }

        while (iterator.hasNext()) {
            CfgTable cfgTable = iterator.next();
            mapTable.put("name", cfgTable.getDesc());
            mapTable.put("key", cfgTable.getTblName());
            listTable.add(mapTable);
            mapTable = new HashMap<>();//防止key的覆盖问题
        }

        return listTable;
    }


    /**
     * @return 返回最后验证完成后的所有列
     * @Description: 验证前端传进来的字段并验证返回
     * @Param [pairingUpload] 封装了表名的一个实体对象
     * @date: 2019/8/15 14:28
     */
    @Override
    public List<Map<String, Object>> validationColumn(DataPairingUpload pairingUpload) {

        int flag = 1;

        List<Map<String, Object>> columnList = new ArrayList<>();
        Map<String, Object> notNullMap = new HashMap<>();
        Map<String, Object> relationMap = new HashMap<>();
        Map<String, Object> checkMainMap = new HashMap<>();
        Map<String, Object> cfgColumnsMap = new HashMap<>();

        List<Map<String, Object>> validationList = dataPairingFillDao.validationColumn(pairingUpload);
        List<CfgColumn> cfgColumns = (List<CfgColumn>) validationList.get(0).get("cfgColumns");
        List<Map<String, Object>> listMap = (List<Map<String, Object>>) validationList.get(0).get("listMap");

        //如果列规则为空
        //只返回所有普通列
        if (listMap == null) {
            Map<String, Object> normalColumnMap = new HashMap<>();
            List<Map<String, Object>> normalList = new ArrayList<>();
            for (CfgColumn normalColumn : cfgColumns) {

                normalColumnMap.put("type", normalColumn.getDataType());
                normalColumnMap.put("key", normalColumn.getName());
                normalColumnMap.put("name", normalColumn.getDescript());
                normalColumnMap.put("length", normalColumn.getColumnLength());
                normalColumnMap.put("value", "");
                normalList.add(normalColumnMap);
                normalColumnMap = new HashMap<>();

            }
            return normalList;
        }
        //如果规则不为空
        //校验列规则
        for (int i = 0; i < listMap.size(); i++) {
            //TODO 如果列的规则变成里面还要嵌套一个json数组的时候再使用这种解析
//            Map<String, Object> mapJudge = null;
//            if (listMap.get(i).size() < 100) {
//                mapJudge = listMap.get(i);
//            } else {
//                JSONArray jsonArray = new JSONArray();
//                for (int j = 0; j < listMap.get(i).size(); j++) {
//
//                    mapJudge = jsonArray.getJSONObject(j);
//
//                }
//            }
            Map<String, Object> mapJudge = listMap.get(i);
            String type = (String) mapJudge.get("type");

            //判断规则的几种情况
            if ("isNotNull".equalsIgnoreCase(type)) {
                String column = (String) mapJudge.get("column");
                if (!"".equals(column)) {
                    String[] stringColumn = column.split(",");
                    for (String s : stringColumn) {
                        for (CfgColumn cfgColumn : cfgColumns) {
                            if (cfgColumn.getName().equalsIgnoreCase(s)) {

                                notNullMap.put("length", cfgColumn.getColumnLength());
                                notNullMap.put("type", cfgColumn.getDataType());
                                notNullMap.put("key", cfgColumn.getName());
                                notNullMap.put("name", cfgColumn.getDescript());
                                notNullMap.put("flag", "notnull");
                                notNullMap.put("value", "");
                                columnList.add(notNullMap);
                                notNullMap = new HashMap<>();//防止key相同出现覆盖
                            }
                        }
                    }
                }
            } else if ("isIncidenceRelation".equalsIgnoreCase(type) || "isCheckMain".equalsIgnoreCase(type)) {
                String column = (String) mapJudge.get("column");
                for (CfgColumn cfgColumn : cfgColumns) {
                    if (cfgColumn.getName().equalsIgnoreCase(column)) {

                        relationMap.put("length", cfgColumn.getColumnLength());
                        relationMap.put("type", cfgColumn.getDataType());
                        relationMap.put("key", cfgColumn.getName());
                        relationMap.put("name", cfgColumn.getDescript());
                        relationMap.put("flag", "primarykey");
                        relationMap.put("value", "");

                        //防止出现isIncidenceRelation和isNotNull中字段重复输出的问题
                        for (int j = 0; j < columnList.size(); j++) {
                            if (relationMap.get("key").equals(columnList.get(j).get("key"))) {
                                flag = 0;
                                break;
                            }
                        }
                        if (flag == 1) {
                            columnList.add(relationMap);
                            relationMap = new HashMap<>();//防止key相同出现覆盖
                        }
                        flag = 1;
                    }
                }
            } else if ("isCompositeCheckMain".equalsIgnoreCase(type)) {

                String jsonString = JSON.toJSONString(mapJudge.get("rules"));
                List<Map<String, Object>> mapRules = JSON.parseObject(jsonString, List.class);
                //处理rules规则
                for (int j = 0; j < mapRules.size(); j++) {
                    String column = (String) mapRules.get(j).get("column");
                    for (CfgColumn cfgColumn : cfgColumns) {

                        if (column.equalsIgnoreCase(cfgColumn.getName())) {
                            checkMainMap.put("type", cfgColumn.getDataType());
                            checkMainMap.put("key", cfgColumn.getName());
                            checkMainMap.put("name", cfgColumn.getDescript());
                            checkMainMap.put("flag", "primarykey");
                            checkMainMap.put("length", cfgColumn.getColumnLength());
                            checkMainMap.put("value", "");

                            //防止出现isCompositeCheckMain和isNotNull中字段重复输出的问题
                            for (int k = 0; k < columnList.size(); k++) {
                                if (checkMainMap.get("key").equals(columnList.get(j).get("key"))) {
                                    flag = 0;
                                    break;
                                }
                            }
                            if (flag == 1) {
                                columnList.add(checkMainMap);
                                checkMainMap = new HashMap<>();//防止key相同出现覆盖
                            }
                            flag = 1;

                        }
                    }
                }
            }

        }
        List<Map<String, Object>> resultList = new ArrayList<>();
        //判断选择的表的是否有新增的字段
        //这个新增字段不输出
        List<LatestColumn> latestColumns = latestColumnRepository.findLatestColumnsByTableRealName(pairingUpload.getTableName());

        if (latestColumns != null) {

            for (CfgColumn cfgColumn : cfgColumns) {
                int status = 1;
                for (LatestColumn latestColumn : latestColumns) {
                    if (latestColumn.getInsertColumn().equalsIgnoreCase(cfgColumn.getName())) {
                        status = 0;
                        continue;
                    }
                }

                if (status == 1) {

                    cfgColumnsMap = getCfgColumnMap(columnList, cfgColumnsMap, resultList, cfgColumn);

                } else {

                }
            }

        } else {
            for (CfgColumn cfgColumn : cfgColumns) {

                cfgColumnsMap = getCfgColumnMap(columnList, cfgColumnsMap, resultList, cfgColumn);

            }
        }
        LOGGER.info("" + columnList);
        return resultList;
    }

    /**
     * @return java.util.Map<java.lang.String                                                                                                                               ,                                                                                                                               java.lang.Object>
     * @Description: 抽取拼接Map的重复代码
     * @Param [columnList, cfgColumnsMap, resultList, cfgColumn]
     * @date: 2019/8/20 21:18
     */

    private Map<String, Object> getCfgColumnMap(List<Map<String, Object>> columnList, Map<String, Object> cfgColumnsMap, List<Map<String, Object>> resultList, CfgColumn cfgColumn) {

        cfgColumnsMap.put("type", cfgColumn.getDataType());
        cfgColumnsMap.put("key", cfgColumn.getName());
        cfgColumnsMap.put("name", cfgColumn.getDescript());
        cfgColumnsMap.put("flag", "");
        cfgColumnsMap.put("length", cfgColumn.getColumnLength());
        cfgColumnsMap.put("value", "");
        for (Map<String, Object> map : columnList) {
            if (cfgColumn.getName().equalsIgnoreCase((String) map.get("key"))) {
                cfgColumnsMap.put("flag", map.get("flag"));
            }
        }
        resultList.add(cfgColumnsMap);
        cfgColumnsMap = new HashMap<>();
        return cfgColumnsMap;
    }


    /**
     * @return boolean 是日期格式：true 不是日期格式:false
     * @Description: 判断传入的参数是否是日期格式
     * @Param [columnValue] 列的值
     * @date: 2019/8/15 14:29
     */
    public boolean isDateFormat(String columnValue) {

        boolean convertSuccess = true;
        //格式传入必须为形如2015-06-17 19:33:49类型
        SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        try {
            format.setLenient(false);
            format.parse(columnValue);
        } catch (ParseException e) {
            convertSuccess = false;
            LOGGER.info("" + e);
        }
        return convertSuccess;
    }

    /**
     * @return boolean 是数字格式：true 不是数字格式:false
     * @Description: 判断传入的参数是否是数字格式
     * @Param [columnValue] 列的值
     * @date: 2019/8/15 14:29
     */
    public boolean isNumberFormat(String columnValue) {

        //判断是否为数字格式
        final String reg = "\\d+\\.{0,1}\\d*";
        boolean isNumber = columnValue.matches(reg);
        return isNumber;
    }

    /**
     * @return 返回的是校验过后的结果List, 并且其中存的都是Map数据
     * @Description: 进行普通字段的校验，比如数字、日期格式
     * @Param resultList 一个存结果的List
     * @Param entry 一个map的entry
     * @Param pairingUpload 封装了表名的一个实体对象
     * @date: 2019/8/15 14:33
     */

    public List<Map<String, Object>> normalColumnValidation(List<Map<String, Object>> resultList, Map.Entry<String, Object> entry, DataPairingUpload pairingUpload) {


        Map<String, Object> normalMap = new HashMap<>();
        List<CfgColumn> cfgColumns = cfgColumnRepository.findByCfgTableTblName(pairingUpload.getTableName());

        String keyColumn = entry.getKey();//列的Key
        String valueColumn = (String) entry.getValue();//列的value

        //如果当前这个值不是为空的时候才进行普通字段的校验
        //如果为空就不管
        if (!"".equalsIgnoreCase((String) entry.getValue())) {
            for (CfgColumn cfgColumn : cfgColumns) {
                //列名和传入的参数Key相同时
                if (keyColumn.equalsIgnoreCase(cfgColumn.getName())) {
                    //判断列的类型
                    //数字类型
                    if (("decimal".equalsIgnoreCase(cfgColumn.getDataType()) || "NUMERIC".equalsIgnoreCase(cfgColumn.getDataType())) && !isNumberFormat(valueColumn)) {
                        normalMap.put("name", keyColumn);
                        normalMap.put("type", cfgColumn.getDataType());
                        normalMap.put("message", cfgColumn.getDescript() + "应该为数字格式");
                        normalMap.put("result", "number");
                        resultList.add(normalMap);
                        normalMap = new HashMap<>();
                        pairingUpload.setState(0);
                    }
                    //日期类型
                    if ("DATETIME".equalsIgnoreCase(cfgColumn.getDataType()) && !isDateFormat(valueColumn)) {
                        normalMap.put("name", keyColumn);
                        normalMap.put("type", cfgColumn.getDataType());
                        normalMap.put("message", cfgColumn.getDescript() + "应该为日期格式");
                        normalMap.put("result", "date");
                        resultList.add(normalMap);
                        normalMap = new HashMap<>();
                        pairingUpload.setState(0);
                    }
                }
                //打印某个不能通过校验的字段
                System.out.println("state:" + pairingUpload.getState() + "   columnName:" + entry.getValue());
            }
        }
        return resultList;
    }

    /**
     * @return boolean
     * @Description: 判断一个字符串中是否包含数字
     * @Param [content] 传入需要判断的字符串
     * @date: 2019/8/22 13:50
     */
    public boolean judgeStrContainDigital(String content) {

        boolean flag = false;
        Pattern p = Pattern.compile(".*\\d+.*");
        Matcher m = p.matcher(content);
        if (m.matches()) {
            flag = true;
        }
        return flag;
    }

    /**
     * @return 返回新增数据过后的一些结果返回
     * @Description: 用户新增数据插入前置机和中央仓的方法
     * @Param map 传入的一个map存储键值对结构数据
     * @Param pairingUpload 封装了表名的一个实体对象
     * @Param resultList 存储结果的一个List
     * @Param resultMap 存储结果的一个Map
     * @date: 2019/8/15 14:38
     */
    @Override
    public List<Map<String, Object>> insertToMysqlAndWareHouse(Map<String, Object> map, DataPairingUpload pairingUpload, List<Map<String, Object>> resultList, Map<String, Object> resultMap) {

        //初始化状态为1
        pairingUpload.setState(1);
        CfgTable cfgTable = dataPairingFillDao.getCfgTable(pairingUpload);

        //解析前端json数据
        String jsonStrValue = (String) map.get("map");
        Map<String, Object> parameterMap = JSON.parseObject(jsonStrValue, LinkedHashMap.class);

        Map<String, Object> mysqlMap = new ConcurrentHashMap<>();
        Map<String, Object> oracleMap = new ConcurrentHashMap<>();
        String columnRuleSet = cfgTable.getCoulmnRuleSet();
        List<Map<String, Object>> listMap = null;

        //如果字段规则不为空的时候
        if (columnRuleSet != null) {
            listMap = JSON.parseObject(columnRuleSet, List.class);
            for (Map.Entry<String, Object> entry : parameterMap.entrySet()) {
                for (int i = 0; i < listMap.size(); i++) {
                    Map<String, Object> mapJudge = listMap.get(i);
                    String type = (String) mapJudge.get("type");

                    //几种需要校验前端插入字段的情况
                    //都是取中央仓进行查询校验
                    //isNotNull 和外键校验
                    if ("isNotNull".equalsIgnoreCase(type)) {
                        String column = (String) mapJudge.get("column");
                        if (!"".equals(column)) {
                            String[] stringColumn = column.split(",");
                            for (String s : stringColumn) {

                                if ("".equals(entry.getValue()) && entry.getKey().equalsIgnoreCase(s)) {
                                    LOGGER.info(entry.getValue() + "的数据为空!");
                                    resultMap.put("message", s + "数据为空");
                                    resultMap.put("code", 404);
                                    resultMap.put("key", s);
                                    resultMap.put("result", "failure");
                                    //加入到返回结果List
                                    resultList.add(resultMap);
                                    //防止key相同的覆盖问题
                                    resultMap = new HashMap<>();
                                    //标志为0
                                    pairingUpload.setState(0);
                                    break;
                                }
                            }

                        }
                    } else if ("isIncidenceRelation".equalsIgnoreCase(type) || "isCheckMain".equalsIgnoreCase(type)) {
                        String column = (String) mapJudge.get("column");
                        String toTable = (String) mapJudge.get("toTable");
                        String toColumn = (String) mapJudge.get("toColumn");
                        //目标表中列的中文名
                        String toColumnName = null;
                        //目标表的中文名
                        String toTableName = null;
                        //目标表的实体对象
                        CfgTable tableObj = cfgTableRepository.findByTblName(toTable);
                        List<CfgColumn> columns = null;
                        //其中不包含字典表的才进行查询
                        if (!judgeStrContainDigital(toTable)) {
                            columns = cfgColumnRepository.findByCfgTableTblName(toTable);
                        }
                        //获取列的中文名
                        if (columns != null) {
                            for (CfgColumn cfgColumn : columns) {
                                if (cfgColumn.getName().equalsIgnoreCase(toColumn)) {
                                    toColumnName = cfgColumn.getDescript();
                                }
                            }
                        } else {
                            toColumnName = toColumn;
                        }

                        if (!Objects.isNull(tableObj)) {
                            toTableName = tableObj.getDesc();
                        } else {
                            toTableName = toTable;
                        }

                        if (column.equalsIgnoreCase(entry.getKey())) {
                            String wareSql = asyncSaveDataService.buildQueryWareSql(toTable, toColumn);
                            //传入的map中的value只要在中央仓中能够查询到值说明存在该外键
                            Map<String, Object> mapCode = new HashMap<>();
                            mapCode.put(toColumn, entry.getValue());
                            List list = synWarehouseDataService.warehouseColumn(wareSql, mapCode);
                            //if (!Objects.nonNull(list)) {
                            if (list.size() == 0) {
                                LOGGER.info(toTable + "中无对应主键");
                                resultMap.put("code", 404);
                                resultMap.put("message", "表" + toTableName + "中" + toColumnName + "无相同值对应匹配,请先填写该张表!");
                                resultMap.put("key", entry.getKey());
                                resultMap.put("result", "failure");
                                //加入到返回结果List
                                resultList.add(resultMap);
                                //防止key相同的覆盖问题
                                resultMap = new HashMap<>();
                                //标志为0
                                pairingUpload.setState(0);
                            }

                        }

                    } else if ("isCompositeCheckMain".equalsIgnoreCase(type)) {

                        String toTable = (String) mapJudge.get("toTable");
                        String jsonString = JSON.toJSONString(mapJudge.get("rules"));
                        List<Map<String, Object>> mapRules = JSON.parseObject(jsonString, List.class);
                        CfgTable tableObj = cfgTableRepository.findByTblName(toTable);
                        List<CfgColumn> columns = null;
                        //目标表的中文名
                        String toTableName = null;
                        //目标表中列的中文名
                        String toColumnName = null;
                        //如果没有包含字典表才进行查询
                        //不然字典表是无法查询得到列的中文名
                        if (!judgeStrContainDigital(toTable)) {
                            columns = cfgColumnRepository.findByCfgTableTblName(toTable);
                        }
                        if (!Objects.isNull(tableObj)) {
                            toTableName = tableObj.getDesc();
                        } else {
                            toTableName = toTable;
                        }

                        //处理rules规则
                        for (int j = 0; j < mapRules.size(); j++) {
                            String column = (String) mapRules.get(j).get("column");
                            String toColumn = (String) mapRules.get(j).get("toColumn");
                            if (columns != null) {
                                for (CfgColumn cfgColumn : columns) {
                                    if (cfgColumn.getName().equalsIgnoreCase(toColumn)) {
                                        toColumnName = cfgColumn.getDescript();
                                    }
                                }
                            } else {
                                toColumnName = toColumn;
                            }

                            if (column.equalsIgnoreCase(entry.getKey())) {
                                String wareSql = asyncSaveDataService.buildQueryWareSql(toTable, toColumn);
                                //传入的map中的value只要在中央仓中能够查询到值说明存在该外键
                                Map<String, Object> mapCode = new HashMap<>();
                                mapCode.put(toColumn, entry.getValue());
                                List list = synWarehouseDataService.warehouseColumn(wareSql, mapCode);
                                //if (Objects.isNull(list)) {
                                if (list.size() == 0) {
                                    LOGGER.info(toTable + "中无对应主键");
                                    resultMap.put("message", "表" + toTableName + "中" + toColumnName + "无相同值对应匹配,请先填写该张表!");
                                    resultMap.put("code", 404);
                                    resultMap.put("key", entry.getKey());
                                    resultMap.put("result", "failure");
                                    //加入到返回结果List
                                    resultList.add(resultMap);
                                    //防止key相同的覆盖问题
                                    resultMap = new HashMap<>();
                                    //标志为0
                                    pairingUpload.setState(0);
                                }
                            }

                        }
                    }

                    //打印一个标志看是否字段没有经过正确的校验
                    System.out.println("state:" + pairingUpload.getState() + "   columnName:" + entry.getValue());
                }

                //列规则校验完毕
                //进行日期数字格式类型校验
                resultList = normalColumnValidation(resultList, entry, pairingUpload);
                //状态不等于0才进行构建sqlMap
                if (pairingUpload.getState() != 0) {
                    mysqlMap.put(entry.getKey().trim(), entry.getValue());
                    oracleMap.put(entry.getKey().trim(), entry.getValue());
                }
            }
        }

        //如果字段规则为空的时候
        if (columnRuleSet == null) {
            for (Map.Entry<String, Object> entry : parameterMap.entrySet()) {

                //进行日期数字格式类型校验
                resultList = normalColumnValidation(resultList, entry, pairingUpload);
                //状态不等于0才进行构建
                if (pairingUpload.getState() != 0) {
                    mysqlMap.put(entry.getKey().trim(), entry.getValue());
                    oracleMap.put(entry.getKey().trim(), entry.getValue());
                }

                //打印一个标志看是否字段没有经过正确的校验
                System.out.println("state:" + pairingUpload.getState() + "   columnName:" + entry.getValue());

            }
            System.out.println("oracleMap:" + oracleMap);
            System.out.println("mysqlMap:" + mysqlMap);

        }


        if (pairingUpload.getState() == 1) {


            //对最新增的字段进行判断修改
            CompareLatestInsertColumn(pairingUpload, mysqlMap, oracleMap);

            System.out.println("oracleMap:" + oracleMap);
            System.out.println("mysqlMap:" + mysqlMap);

            //mysql插入语句
            String mysqlInsertSql = asyncSaveDataService.buildInsertSql(pairingUpload.getTableName(), "mysql");
            //oracle插入语句
            String synWarehouseInsertSql = asyncSaveDataService.getSynWarehouseInsertSql(pairingUpload.getTableName());
            //插入数据到中央仓库wareHouseData
            int oracleRows = synWarehouseDataService.synWarehouseData(oracleMap, synWarehouseInsertSql);
            //构建sql语句并插入到medical_business_data数据库
            int mysqlRows = synDaoImpl.insertTableData(mysqlInsertSql, mysqlMap);

            System.out.println("mysql影响了:" + mysqlRows + "行");
            System.out.println("oracle影响了:" + oracleRows + "行");
            if (oracleRows > 0 && mysqlRows > 0) {

                //新增的仓库数据（以_INT结尾的）是保存对应字段的（非_INT）的值的整型

                resultMap.put("code", 200);
                resultMap.put("message", "新增数据成功");
                resultMap.put("result", "success");
                resultList.add(resultMap);//加入到返回结果List
            } else {
                resultMap.put("code", 500);
                resultMap.put("message", "新增数据失败");
                resultMap.put("result", "error");
                resultList.add(resultMap);//加入到返回结果List
            }


        }
        //返回前端的字段校验结果
        //校验无误:返回 null
        //校验有误:返回校验失败的字段
        return resultList;

    }

    /**
     * @return void
     * @Description: 比对最新增的数据库字段
     * @Param pairingUpload 一个存储了表名的实体对象
     * @Param mysqlMap 存储jpa拼接的数据Map
     * @Param oracleMap 存储jpa拼接的数据Map
     * @date: 2019/8/22 10:40
     */

    private void CompareLatestInsertColumn(DataPairingUpload pairingUpload, Map<String, Object> mysqlMap, Map<String, Object> oracleMap) {

        List<LatestColumn> latestColumns = latestColumnRepository.findLatestColumnsByTableRealName(pairingUpload.getTableName());
        //构建一个map方便比对遍历
        Map<String, Object> mapCount = new HashMap<>();
        for (Map.Entry<String, Object> entry : mysqlMap.entrySet()) {
            mapCount.put(entry.getKey().trim(), entry.getValue());
        }

        if (latestColumns != null) {

            for (Map.Entry<String, Object> entry : mapCount.entrySet()) {
                for (LatestColumn latestColumn : latestColumns) {

                    //如果数据类型是number都将其对应date类型转换为Int类型
                    if ("NUMBER".equalsIgnoreCase(latestColumn.getDateType())) {
                        //新增的NUMBER类型字段分了三种情况
                        if (latestColumn.getInsertColumn().replace("_INT", "").equalsIgnoreCase(entry.getKey())) {

                            String valueInt = ((String) entry.getValue()).replaceAll("-+", "").substring(0, 8);
                            mysqlMap.put(latestColumn.getInsertColumn().trim(), valueInt);
                            oracleMap.put(latestColumn.getInsertColumn().trim(), valueInt);

                        } else if (latestColumn.getInsertColumn().replace("_DAY", "").equalsIgnoreCase(entry.getKey())) {

                            String valueDay = ((String) entry.getValue()).replaceAll("-+", "").substring(0, 8);
                            mysqlMap.put(latestColumn.getInsertColumn().trim(), valueDay);
                            oracleMap.put(latestColumn.getInsertColumn().trim(), valueDay);

                        } else if (latestColumn.getInsertColumn().replace("_YEAR", "").equalsIgnoreCase(entry.getKey())) {

                            String valueYear = ((String) entry.getValue()).replaceAll("-+", "").substring(0, 4);
                            mysqlMap.put(latestColumn.getInsertColumn().trim(), valueYear);
                            oracleMap.put(latestColumn.getInsertColumn().trim(), valueYear);
                        }

                        if ("LATEST".equalsIgnoreCase(latestColumn.getInsertColumn())) {
                            mysqlMap.put(latestColumn.getInsertColumn().trim(), 1);
                            oracleMap.put(latestColumn.getInsertColumn().trim(), 1);
                        }
                    }

                    //varchar类型分了三种情况
                    else if ("VARCHAR".equalsIgnoreCase(latestColumn.getDateType())) {

                        //只有DISEASE_CATEGORY字段
                        //这个字段的有三张表
                        if ("DISEASE_CATEGORY".equalsIgnoreCase(latestColumn.getInsertColumn())) {
                            //如果这个表是 门(急)诊病历(OUTPATIENT_EMERGENCY_RECORD) 时
                            if ("OUTPATIENT_EMERGENCY_RECORD".equalsIgnoreCase(pairingUpload.getTableName())) {
                                //PRELIM_WESTERN_DIAG_CODE取前5位加两个0，没有值填"-"
                                if ("PRELIM_WESTERN_DIAG_CODE".equalsIgnoreCase(entry.getKey())) {
                                    //进行sqlMap的拼接
                                    repeateJudgeCode(mysqlMap, oracleMap, entry);
                                }
                                //如果这个表是 住院病案首页(INPATIENT_MEDICAL_RECORD) 时
                            } else if ("INPATIENT_MEDICAL_RECORD".equalsIgnoreCase(pairingUpload.getTableName())) {
                                //C03C取前5位加两个0，没有值填"-"，没有值填"-"
                                if ("C03C".equalsIgnoreCase(entry.getKey())) {
                                    //进行sqlMap的拼接
                                    repeateJudgeCode(mysqlMap, oracleMap, entry);
                                }
                            }
                            //如果这个表是 中医病案首页(INPATIENT_TCM_RECORD) 时
                            else if ("INPATIENT_TCM_RECORD".equalsIgnoreCase(pairingUpload.getTableName())) {
                                //ZYZD_JBBM取前5位加两个0，没有值填"-"，没有值填"-"
                                if ("ZYZD_JBBM".equalsIgnoreCase(entry.getKey())) {
                                    //进行sqlMap的拼接
                                    repeateJudgeCode(mysqlMap, oracleMap, entry);
                                }
                            }
                        } else if (latestColumn.getInsertColumn().replace("_MONTH", "").equalsIgnoreCase(entry.getKey())) {
                            //判断以_MONTH结尾的
                            ConcatYearMonth(mysqlMap, oracleMap, entry, latestColumn);

                        } else if ("UPDATE_DATE".equalsIgnoreCase(entry.getKey())) {
                            //判断biz_month形式不一样，存的是月份2019M06
                            ConcatYearMonth(mysqlMap, oracleMap, entry, latestColumn);
                        }

                    }

                }

            }
        }

    }

    /**
     * @return void
     * @Description: 一段重复截取的代码
     * @Param mysqlMap 存储jpa拼接的数据Map
     * @Param oracleMap 存储jpa拼接的数据Map
     * @date: 2019/8/20 22:40
     */

    private void repeateJudgeCode(Map<String, Object> mysqlMap, Map<String, Object> oracleMap, Map.Entry<String, Object> entry) {

        //value有值
        String resultValue = (String) entry.getValue();
        substringFiveBitOrFillLine(mysqlMap, oracleMap, resultValue);
    }

    /**
     * @return void
     * @Description: 抽取重复拼接年月的重复代码
     * @Param mysqlMap 存储jpa拼接的数据Map
     * @Param oracleMap 存储jpa拼接的数据Map
     * @Param latestColumn 新增的列字段
     * @date: 2019/8/20 21:15
     */
    private void ConcatYearMonth(Map<String, Object> mysqlMap, Map<String, Object> oracleMap, Map.Entry<String, Object> entry, LatestColumn latestColumn) {

        //截取四位年
        String fourBitYear = ((String) entry.getValue()).replaceAll("-+", "").substring(0, 4).concat("M");
        //截取两位月
        String twoBitMonth = ((String) entry.getValue()).replaceAll("-+", "").substring(4, 6);
        //进行新格式年月的拼接
        String newYearMonthFormat = fourBitYear.concat(twoBitMonth);

        mysqlMap.put(latestColumn.getInsertColumn().trim(), newYearMonthFormat);
        oracleMap.put(latestColumn.getInsertColumn().trim(), newYearMonthFormat);
    }


    /**
     * @return void
     * @Description: 截取前五位或者没有就填写'-'
     * @Param mysqlMap 存储jpa拼接的数据Map
     * @Param oracleMap 存储jpa拼接的数据Map
     * @Param resultValue 返回最后截取完的值
     * @date: 2019/8/22 10:43
     */
    private void substringFiveBitOrFillLine(Map<String, Object> mysqlMap, Map<String, Object> oracleMap, String resultValue) {

        if (!"".equals(resultValue) && resultValue.length() >= 5) {
            String diseaseConcat = resultValue.substring(0, 5).concat("0").concat("0");
            mysqlMap.put("DISEASE_CATEGORY", diseaseConcat);
            oracleMap.put("DISEASE_CATEGORY", diseaseConcat);

        } else if (!"".equals(resultValue) && resultValue.length() < 5) {

            String diseaseConcat = resultValue.concat("0").concat("0");
            mysqlMap.put("DISEASE_CATEGORY", diseaseConcat);
            oracleMap.put("DISEASE_CATEGORY", diseaseConcat);
        } else {
            //没有值填"-"
            mysqlMap.put("DISEASE_CATEGORY", "-");
            oracleMap.put("DISEASE_CATEGORY", "-");
        }

    }


    /**
     * @return 返回最后分页查询的所有数据
     * @Description: 根据表名进行查询分页
     * @Param pageable 封装了分页相关参数的对象
     * @Param pairingUpload 封装了表名的一个实体对象
     * @Param result 返回最后的结果
     * @date: 2019/8/15 14:40
     */
    @Override
    public Map<String, Object> listByTableName(Pageable pageable, DataPairingUpload pairingUpload, Map<String, Object> result) {

        return dataPairingFillDao.listByTableName(pageable, pairingUpload, result);
    }

    /**
     * @return 返回所有的列给用户
     * @Description: 得到所有的列名
     * @Param pairingUpload 封装了表名的一个实体对象
     * @Param list 用来存储最后的结果Map
     * @Param map 存储最后的实际结果
     * @date: 2019/8/15 14:42
     */
    @Override
    public List<Map<String, Object>> getColumnName(DataPairingUpload pairingUpload, List<Map<String, Object>> list, Map<String, Object> map) {


        return dataPairingFillDao.getColumnName(pairingUpload, list, map);
    }

    /**
     * @return 返回选择列的所有详情字段的值
     * @Description: 点击详情进行字段详情展示
     * @Param hashMap 存储要返回的Map结果集
     * @Param columnId 通过列ID查询所有进行详情的展示
     * @Param pairingUpload  封装了表名的一个实体对象
     * @date: 2019/8/15 14:44
     */
    @Override
    public List<Map<String, Object>> listDetail(Map<String, Object> hashMap, Long columnId, DataPairingUpload pairingUpload) {

        int i = 0;
        //构造sql语句
        String buildString = asyncQueryDataService.buildQuerySqlByColumnId(columnId, pairingUpload.getTableName());
        List<Map<String, Object>> mapList = synDaoImpl.queryTableColumnDetail(buildString);
        List<Map<String, Object>> listResult = new ArrayList<>();
        List<CfgColumn> cfgColumns = dataPairingFillDao.listDetail(hashMap, columnId, pairingUpload);
        Map<String, Object> map = mapList.get(0);
        Set<Map.Entry<String, Object>> entrySet = map.entrySet();

        //一个状态标记
        int status = 0;
        for (Map.Entry<String, Object> set : entrySet) {

            if (i <= cfgColumns.size() - 1) {
                hashMap.put("key", set.getKey());
                hashMap.put("value", set.getValue());
                System.out.println(set.getKey() + "-->" + set.getValue());
                //考虑name在数据库中不对应的问题
                for (int j = 0; j < cfgColumns.size(); j++) {
                    if (!StringUtils.isEmpty(cfgColumns.get(j).getName())) {

                        //判断业务表和cfgColumn属性表中的字段之间是否对应
                        if (cfgColumns.get(j).getName().equalsIgnoreCase(set.getKey())) {
                            hashMap.put("name", cfgColumns.get(j).getDescript());
                            status = 1;

                        }
                    }
                }
                if (status == 0)
                    hashMap.put("name", "");

                listResult.add(hashMap);
                i++;
                //防止key覆盖
                hashMap = new HashMap<>();
            }
        }
        return listResult;
    }
}
